import axios from 'axios';
import { Loading} from 'element-ui';
import project from '@/core/project';
import qs from 'qs';

axios.defaults.baseURL = project.BASE_URL;
axios.defaults.timeout = 60000; // 响应时间


// 请求拦截器
axios.interceptors.request.use(
    config => {
        // config.headers['api-version'] = project.APP_VERSION;
        // config.headers['lang'] = project.APP_LANG;
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);
// 返回拦截器
axios.interceptors.response.use(
    response => {
            return response;
    },
    error => {
        console.log(error);
        return {code: '-00001', msg: ''}; // 返回接口返回的错误信息
    });

function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(`${url}?${qs.stringify(params)}`, {}).then(response => {
            resolve(response.data);
        }).catch(err => {
            reject(err);
        });
    });
}


/**
 * 通过axios下载文件
 * @param url
 * @param param
 */
function downFile(url, param = {}, filename) {
    const load = Loading.service({
        text: '文件生成中...',
        background: 'rgba(255,255,255,0.8)'
    });
    axios({
        method: 'post',
        data: param,
        url: url,
        responseType: 'blob'
    }).then(res => {
        var url = window.URL.createObjectURL(new Blob([res]));
        var link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', filename);    // 自定义下载文件名（如exemple.txt）
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
            document.body.removeChild(link);
            load.close();
        }, 1000);
    })
}

function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error);
        });
    });
}

function postForm(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, qs.stringify(params)).then(response => {
            resolve(response);
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error);
        });
    });
}

function put(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(response => {
                resolve(response);
            })
            .catch(err => {
                reject(err);
            });
    });
}

function del(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.delete(url, params)
            .then(response => {
                resolve(response);
            })
            .catch(err => {
                reject(err);
            });
    });
}


export default {
    del,
    get,
    put,
    post,
    postForm,
    downFile
};
